<?php

namespace Lib\Core;

class Script extends \Home {

    private $parameters = array();

    public function __construct() {
        global $argv;
        $this->setParams($argv);
    }

    public function getParam($key) {
        if (isset($this->parameters[$key])) {
            return $this->parameters[$key];
        }
        return null;
    }

    public function getParams() {
        return $this->parameters;
    }

    /**
     * 如果要启动多进程使用 --processes 参数指定进程个数.
     * @throws \Exception
     */
    public function run() {
        $run = $this->getParam('run');
        $function = $this->getParam('function');
        if (!$run) {
            throw new \Exception('miss parameter "run"');
        }
        if (!$function) {
            throw new \Exception('miss parameter "function"');
        }
        $className = '\\Run\\' . $run;
        $class = $className::instance();
        $parameters = $this->getParams();
        unset($parameters['run']);
        unset($parameters['function']);
        $processNumber = $this->getParam('process');
        if ($processNumber) {
            $daemon = \Lib\Core\JobDaemon::instance();
            $daemon->registerChildProcess(array($class, $function), $processNumber, $parameters);
            $daemon->run();
        } else {
            call_user_func(array($class, $function), $parameters);
        }
    }

    private function setParams($argv) {
        array_shift($argv);
        if (!$argv) {
            return;
        }
        foreach ($argv as $val) {
            $val = str_replace('.', '\\', $val);
            if (strpos($val, '--') !== 0) {
                continue;
            }
            $len = mb_strpos($val, '=');
            if (!$len) {
                $key = mb_substr($val, 2);
                $value = null;
            } else {
                $key = mb_substr($val, 2, $len - 2);
                $value = mb_substr($val, $len + 1);
            }
            $this->parameters[$key] = $value;
        }
    }

}